package com.justgame.project.generator.template;

import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.po.TableField;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.justgame.project.generator.container.EntityContainer;
import com.justgame.project.generator.enums.TemplateType;
import com.justgame.project.generator.schema.Entity;
import com.justgame.project.generator.schema.Enumerate;
import com.justgame.project.generator.schema.Field;
import com.justgame.project.generator.utils.AppContextUtils;
import com.justgame.project.generator.utils.NameUtils;

import java.util.*;

public interface ITemplateResolve {
    /**
     * 模板类型
     * @return com.justgame.project.generator.enums.TemplateType
     */
    TemplateType getType();

    /**
     * 构建模板配置
     */
    default FileOutConfig buildConfig(){
        return new FileOutConfig(getTemplateFilePath()) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return getOutputFilePath(tableInfo.getName());
            }
        };
    }

    /**
     * 获取模板文件地址
     */
    String getTemplateFilePath();

    /**
     * 获取文件生成路径
     */
    String getOutputFilePath(String tableName);

    default void tableInfoHandle(TableInfo tableInfo){
        List<TableField> fields = tableInfo.getFields();
        EntityContainer container = AppContextUtils.getBean(EntityContainer.class);
        Entity entity = container.findEntityByTableName(tableInfo.getName()).orElseThrow();
        fields.forEach(tableField -> {
            Map<String,Object> customMap = new HashMap<>();
            Field field = entity.findFieldByName(tableField.getPropertyName()).orElseThrow();
            Optional<Enumerate> optionalEnum = entity.findEnumByFieldName(tableField.getPropertyName());
            customMap.put("EnumTypeName", optionalEnum.map(enumerate -> NameUtils.firstWorldUpper(enumerate.getFieldName())).orElse("null")+"");
            customMap.put("isEncrypt",field.isEncrypt());
            customMap.put("importPkg",tableField.getColumnType().getPkg()+"");
            tableField.setCustomMap(customMap);
        });
    }
}
